import {
	LOGIN_SUCCESS,
	LOGIN_FAILED,
} from '../constants'

import * as Utils from '../utils'

function loginSuccess() {
	return response => ({
		type: LOGIN_SUCCESS,
		response,
	})
}

function loginFailed() {
	return response => ({
		type: LOGIN_FAILED,
		errorMsg: response.errorMessage,
		errorCode: response.errorCode,
	})
}

export function logoutAction() {
	return ({
		type: 'LOGOUT',
	})
}

export function clearErrMsgAction() {
	return ({
		type: 'CLEAR_ERRMSG'
	})
}

export function loginAction(url, requestMethod = 'POST', requestBody = null) {
	let config = {
		mode: 'cors',
		method: requestMethod,
		headers: {
			Accept: 'application/json',
			'Content-Type': 'application/json',
		},
	}

	Object.assign(config, !!requestBody ? { body: JSON.stringify(requestBody) } : {})

	return dispatch => {
		dispatch(
			Utils.restCall(
				url,
				config,
				loginSuccess(),
				loginFailed(),
				true
			)
		)
	}
}